﻿using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;

namespace JinShun.OA.UI.Auth
{
    public class TokenHelper
    {
        //获取token
        private readonly AuthenticationStateProvider AuthenticationStateProvider;

        public TokenHelper(AuthenticationStateProvider authenticationStateProvider)
        {
            AuthenticationStateProvider = authenticationStateProvider;
        }

        public async Task<Dictionary<string, string>> GetTokenAsync()
        {
            try
            {
                var authenticationState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
                var User = authenticationState.User;
                bool isEmpty = !User.Claims.Any();
                if (isEmpty) return null;
                string token = User.Claims.FirstOrDefault(it => it.Type == ClaimTypes.Sid).Value.ToString();
                //获取登陆的信息
                Dictionary<string, string> headers = new Dictionary<string, string>();
                headers.Add("Authorization", "Bearer " + token);
                return headers;
            }
            catch (NullReferenceException ex)
            {
                return null;
            }
        }
    }
}
